import { logger, readFirstLine } from '@ibizlab/template-core';
import { existsSync } from 'fs-extra';

const skipRule = '/* pub-rule @skip-overwrite  */';

export function winToUnixPath(path: string): string {
	return path.replace(/\\/g, '/');
}

export function handleJudgmentExecute(
	context: unknown,
	bol: boolean,
	options: Handlebars.HelperOptions
): string | boolean {
	if (options.fn) {
		return bol ? options.fn(context) : options.inverse(context);
	}
	// eslint-disable-next-line no-return-assign
	return bol ? (options.hash.yes = true) : (options.hash.no = false);
}

/**
 * 判断是否跳过覆盖写入
 *
 * @param {string} filePath 文件路径
 * @return {*}  {Promise<boolean>} true: 跳过文件写入, false: 覆盖写入
 */
export async function skipOverWrite(filePath: string): Promise<boolean> {
	if (existsSync(filePath)) {
		const fistLine = await readFirstLine(filePath);
		if (fistLine === skipRule) {
			logger.info('跳过文件', `${filePath}`);
			return true;
		}
	}
	return false;
}
